package com.tgpms.interfaces.properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.stereotype.Component;
import org.springframework.util.StringValueResolver;
/*
 *TODO
 */
@Component
public class UrlTest implements ApplicationContextAware ,EmbeddedValueResolverAware{


    private static Logger logger = LoggerFactory.getLogger(UrlTest.class);

    // Spring应用上下文环境
    private static ApplicationContext applicationContext;

    private static StringValueResolver stringValueResolver;

    /**
     * 实现ApplicationContextAware接口的回调方法。设置上下文环境
     *
     * @param applicationContext
     */
    public void setApplicationContext(ApplicationContext applicationContext) {
        UrlTest.applicationContext = applicationContext;
    }

    /**
     * @return ApplicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 获取对象
     *
     * @param IP
     * @return Object
     * @throws BeansException
     */
    public static Object getBean(String IP) throws BeansException {
        return applicationContext.getBean(IP);
    }


    /**
     * 动态获取配置文件中的值
     * @param IP
     * @return
     */
    public static String getPropertiesValue(String IP) {
        try {
            IP = "${" + IP + "}";
            return stringValueResolver.resolveStringValue(IP);
        } catch (Exception e) {
            logger.error(String.format("当前环境变量中没有{%s}的配置", IP));
            // 获取失败则返回null
            return null;
        }
    }

    @Override
    public void setEmbeddedValueResolver(StringValueResolver stringValueResolver) {
        this.stringValueResolver = stringValueResolver;
    }
}
